package com.feeyo.groundservice.base_util

import android.app.Activity
import android.util.TypedValue
import android.view.Gravity
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.setPadding
import androidx.fragment.app.Fragment
import coil.load
import coil.transform.RoundedCornersTransformation
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.Utils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.impl.ConfirmPopupView
import com.lxj.xpopup.interfaces.OnCancelListener
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.lxj.xpopup.interfaces.SimpleCallback
import com.lxj.xpopup.interfaces.XPopupCallback
import com.therouter.TheRouter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.regex.Pattern

/**
 *作者：QLH on 2023-09-13
 *描述：原生的扩展函数
 */


fun ImageView.showImage(url: Any?) = this.load(url)

fun ImageView.showImageWithCorner(url: Any?) = this.load(url) {
    transformations(RoundedCornersTransformation(R.dimen.d5.getPxFromResource().toFloat()))
}

/**
 * 修改图标颜色
 * @param color 将要设置成的颜色
 * **/
fun ImageView.setIconColor(color: Int) {
    setColorFilter(color)
}


/**
 * 是否是视频格式文件后缀,mp4
 * @param path url or file path
 */
fun String.isVideoPath(): Boolean {
    val regex = ".*\\.(mp4)"
    val p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)
    return p.matcher(this).matches()
}

fun String?.dealString(): String = if (this.isNullOrEmpty() || this == "null") "- -" else this


fun Activity.keepScreenOn() {
    window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}

fun Activity.clearScreeOn() {
    window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}

/**组合简单路由**/
fun String.getRouterPath() = TheRouter.build(this)

/**获取Fragment路由**/
fun String.getFragmentPath() = this.getRouterPath().createFragment<Fragment>()
    ?: throw NullPointerException("Fragment:[${this}] is null")

/**
 * 显示toast
 */
fun toast(msg: String, gravity: Int? = null) {
    if (AppUtils.isAppForeground())//前台才弹框
        Toast(Utils.getApp()).apply {
            view = TextView(Utils.getApp()).apply {
                setPadding(R.dimen.d5.getPxFromResource())
                text = msg
                setTextColor(R.color.white.getColor())
                setBackgroundResource(R.drawable.shape_custom_loading)
            }
            gravity?.let { setGravity(Gravity.CENTER, 0, 0) }
            duration = Toast.LENGTH_SHORT
        }.show()
}

fun toastCenter(msg: String) {
    toast(msg, Gravity.CENTER)
}


/**获取确认对话框模板**/
fun Any.getConfirmDlg(
    title: String,
    content: String,
    contentColor: Int? = null,
    confirmBtnTxt: String = "确定",
    showCancel: Boolean = true,
    dismissOnTouchOutside: Boolean = true,
    dismissOnBackPressed: Boolean = true,
    cancelBtnTxt: String = "取消",
    cancelListener: SuccessCallback? = null,
    confirmListener: SuccessCallback? = null,
    popupCallback: XPopupCallback? = null,
): ConfirmPopupView? {
    val activity = if (this is Activity) this else ActivityUtils.getTopActivity()

    assert(activity != null) {
        toastCenter("请传入Activity")
        return null
    }

    val builder = XPopup.Builder(activity)
        .isDestroyOnDismiss(true)
        .hasShadowBg(true)//背景色
        .dismissOnTouchOutside(dismissOnTouchOutside)
        .dismissOnBackPressed(dismissOnBackPressed)

    popupCallback?.let {
        builder.setPopupCallback(it)
    } ?: builder.setPopupCallback(object : SimpleCallback() {
        override fun beforeShow(popupView: BasePopupView?) {
            super.beforeShow(popupView)
            (popupView as ConfirmPopupView).let {
                val tv_title = it.javaClass.getDeclaredField("tv_title")
                val tv_content = it.javaClass.getDeclaredField("tv_content")
                val tv_cancel = it.javaClass.getDeclaredField("tv_cancel")
                val tv_confirm = it.javaClass.getDeclaredField("tv_confirm")

                tv_confirm.isAccessible = true
                tv_cancel.isAccessible = true
                tv_content.isAccessible = true
                tv_title.isAccessible = true

                (tv_confirm.get(it) as TextView).apply {
                    setTextColor(R.color.blue_main_2E76EE.getColor())
                    setTextSize(
                        TypedValue.COMPLEX_UNIT_PX,
                        R.dimen.d14.getPxFromResource().toFloat()
                    )
                }
                (tv_cancel.get(it) as TextView).apply {
                    setTextColor(R.color.black_66.getColor())
                    setTextSize(
                        TypedValue.COMPLEX_UNIT_PX,
                        R.dimen.d14.getPxFromResource().toFloat()
                    )
                }
                (tv_title.get(it) as TextView).apply {
                    setTextColor(R.color.black_27.getColor())
                    setTextSize(
                        TypedValue.COMPLEX_UNIT_PX,
                        R.dimen.d20.getPxFromResource().toFloat()
                    )
                }
                (tv_content.get(it) as TextView).apply {
                    setTextColor(contentColor?.getColor() ?: R.color.black_66.getColor())
                    setTextSize(
                        TypedValue.COMPLEX_UNIT_PX,
                        R.dimen.d16.getPxFromResource().toFloat()
                    )
                }
            }
        }
    })
    return builder.asConfirm(title, content, cancelBtnTxt, confirmBtnTxt, OnConfirmListener {
        confirmListener?.success()
    }, OnCancelListener {
        cancelListener?.success()
    }, !showCancel)
}

/**延迟执行 毫秒
 * @param millTime mills
 * **/
fun Any.delayMillToExecute(millTime: Long = 2, method: suspend CoroutineScope.() -> Unit) =
    CoroutineScope(Dispatchers.Main).launch {
        delay(millTime)
        method()
    }


/**替换ip地址为新的
 *
 *
 *https://10.30.155.35/dispatch/ => https://192.168.1.1/dispatch/
 *
 * "https://10.30.155.35/dispatch/".replaceIp("192.168.1.1")
 * **/
fun String.replaceIp(newIp: String): String {
    // 使用正则表达式匹配IP地址
    val ipRegex =
        if (this.contains("\\d{1,3}:\\d{1,8}".toRegex()))//包含端口
            Regex(pattern = """\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,8}""")
        else//不包含端口
            Regex(pattern = """\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}""")
    //替换ip
    val newUrl = ipRegex.replace(this, newIp)
    return newUrl
}


/**替换域名地址为新的
 *
 *
 *http://dispatch-hak-dev.chinaacdm.com/api/  => http://192.168.1.1/api/
 *
 * "http://dispatch-hak-dev.chinaacdm.com/api/".replaceDomain("http://192.168.1.1")
 * **/
fun String.replaceDomain(newDom: String): String {
    val hostRegex = Regex("https?://([^/]+)")
    val newUrl = hostRegex.replace(this, newDom)
    return newUrl
}


/**替换域名地址为新的
 *
 *
 *wss://dispatch-hak-dev.chinaacdm.com/im/ws/  => wss://192.168.1.1/im/ws/
 *
 * "wss://dispatch-hak-dev.chinaacdm.com/im/ws/".replaceDomain("wss://192.168.1.1")
 * **/
fun String.replaceWebsocketDomain(newDom: String): String {
    val hostRegex = Regex("wss?://([^/]+)")
    val newUrl = hostRegex.replace(this, newDom)
    return newUrl
}

fun String?.assertEmpty(msg: String): Boolean {
    if (this.isNullOrEmpty()) {
        toastCenter(msg)
    }
    return this.isNullOrEmpty()
}


/**去除中文（），空格**/
fun String.exIncludeCNParentheses(char1: String = "", char2: String = "") =
    this.replace("（", char1).replace("）", char2)



